import os
import uuid
import json
import requests
import numpy as np
from PIL import Image, ImageDraw, ImageFont
from io import BytesIO
from pathlib import Path
from datetime import datetime
from config import Config

try:
    import tifffile
    TIFFFILE_AVAILABLE = True
except ImportError:
    TIFFFILE_AVAILABLE = False

try:
    from psd_tools import PSDImage
    PSD_TOOLS_AVAILABLE = True
except ImportError:
    PSD_TOOLS_AVAILABLE = False

class PhotoshopTiffProcessor:
    """
    专门处理包含Photoshop图层信息的TIFF文件
    """
    
    def __init__(self):
        self.export_folder = Config.EXPORT_FOLDER
        self.upload_folder = Config.UPLOAD_FOLDER
        
    def extract_photoshop_layers(self, tiff_path):
        """
        从TIFF文件中提取Photoshop图层信息
        """
        layers_info = []
        
        if not TIFFFILE_AVAILABLE:
            print("警告：tifffile未安装，无法提取图层信息")
            return layers_info
        
        try:
            with tifffile.TiffFile(tiff_path) as tif:
                page = tif.pages[0]
                
                # 检查Photoshop数据标签 (34377)
                if 34377 in page.tags:
                    photoshop_data = page.tags[34377].value
                    print(f"找到Photoshop数据: {len(photoshop_data)} 字节")
                    
                    # 尝试解析图层信息
                    layers_info = self._parse_photoshop_layers(photoshop_data, page.shape)
                else:
                    print("未找到Photoshop图层数据")
                    # 作为单层处理
                    layers_info = [{
                        'name': '主图层',
                        'index': 0,
                        'width': page.shape[1],
                        'height': page.shape[0],
                        'visible': True,
                        'blend_mode': 'normal'
                    }]
                    
        except Exception as e:
            print(f"提取图层信息失败: {e}")
            
        return layers_info
    
    def _parse_photoshop_layers(self, photoshop_data, image_shape):
        """
        解析Photoshop数据中的图层信息
        这是一个简化版本，主要提取基本的图层信息
        """
        layers_info = []
        
        try:
            # Photoshop数据的基本解析
            # 这里只是示例，实际的Photoshop数据格式非常复杂
            
            # 检查数据头部
            if len(photoshop_data) < 100:
                print("Photoshop数据太短，无法解析")
                return layers_info
            
            # 估算图层数量（这是一个简化的方法）
            # 实际的解析需要深入了解Photoshop的私有格式
            estimated_layers = self._estimate_layer_count(photoshop_data)
            
            print(f"估算的图层数量: {estimated_layers}")
            
            # 为每个估算的图层创建信息
            for i in range(estimated_layers):
                layers_info.append({
                    'name': f'Photoshop图层_{i+1}',
                    'index': i,
                    'width': image_shape[1],
                    'height': image_shape[0],
                    'visible': True,
                    'blend_mode': 'normal'
                })
                
        except Exception as e:
            print(f"解析Photoshop数据失败: {e}")
            # 回退到单层
            layers_info = [{
                'name': '合并图层',
                'index': 0,
                'width': image_shape[1],
                'height': image_shape[0],
                'visible': True,
                'blend_mode': 'normal'
            }]
        
        return layers_info
    
    def _estimate_layer_count(self, data):
        """
        估算图层数量的简化方法
        """
        # 这是一个非常简化的估算方法
        # 实际的Photoshop格式解析需要专门的库
        
        # 查找可能的图层分隔符或重复模式
        data_size = len(data)
        
        # 基于数据大小的经验估算
        if data_size > 15000:  # 大量数据，可能有多个图层
            return max(2, min(10, data_size // 2000))  # 估算2-10个图层
        elif data_size > 5000:
            return 2  # 可能有2个图层
        else:
            return 1  # 单图层
    
    def create_layered_tiff_with_photoshop_layers(self, template, regions, customization_data):
        """
        创建保留Photoshop图层信息的TIFF文件
        """
        # 1. 获取原始图片和图层信息
        original_image = None
        original_layers_info = []
        canvas_width = template['width']
        canvas_height = template['height']
        
        if template.get('image_path'):
            image_path = template['image_path']
            if Path(image_path).is_absolute():
                template_image_path = Path(image_path)
            else:
                template_image_path = self.upload_folder / image_path
                
            if template_image_path.exists():
                print(f"处理Photoshop TIFF: {template_image_path}")
                
                # 加载原始图片
                original_image = Image.open(template_image_path)
                if original_image.mode != 'RGBA':
                    original_image = original_image.convert('RGBA')
                
                # 使用原始尺寸
                canvas_width, canvas_height = original_image.size
                
                # 提取图层信息
                original_layers_info = self.extract_photoshop_layers(str(template_image_path))
                
                print(f"检测到 {len(original_layers_info)} 个原始图层")
        
        # 2. 处理JSON图片
        json_layers = []
        for region_index, region_data in customization_data.get('regions', {}).items():
            elements = region_data.get('elements', [])
            
            for element_idx, element in enumerate(elements):
                try:
                    json_layer = self._create_json_layer(element, canvas_width, canvas_height)
                    if json_layer:
                        json_layers.append(json_layer)
                        print(f"创建JSON图层 {len(json_layers)}")
                except Exception as e:
                    print(f"创建JSON图层失败: {e}")
        
        # 3. 保存为新的TIFF文件
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        unique_id = str(uuid.uuid4())[:8]
        filename = f"photoshop_layered_{timestamp}_{unique_id}.tif"
        export_path = self.export_folder / filename
        
        return self._save_photoshop_compatible_tiff(
            original_image, original_layers_info, json_layers, export_path
        )
    
    def _create_json_layer(self, element, canvas_width, canvas_height):
        """创建JSON图片图层"""
        image_url = element.get('image_url')
        if not image_url:
            return None
        
        # 下载图片
        element_image = self._download_image_from_url(image_url)
        if not element_image:
            return None
        
        # 应用用户设置
        user_data = element.get('user_placement_data', {})
        element_image = self._apply_transformations(element_image, user_data)
        
        # 创建图层画布
        layer = Image.new('RGBA', (canvas_width, canvas_height), (0, 0, 0, 0))
        
        # 获取位置
        position = user_data.get('position', {})
        x = int(position.get('x', 0))
        y = int(position.get('y', 0))
        
        # 确保不超出边界
        x = max(0, min(x, canvas_width - element_image.width))
        y = max(0, min(y, canvas_height - element_image.height))
        
        # 粘贴到图层
        layer.paste(element_image, (x, y), element_image)
        
        return layer
    
    def _download_image_from_url(self, url):
        """下载图片"""
        try:
            response = requests.get(url, timeout=30)
            response.raise_for_status()
            return Image.open(BytesIO(response.content))
        except Exception as e:
            print(f"下载图片失败 {url}: {e}")
            # 创建红色占位符
            placeholder = Image.new('RGBA', (100, 100), (255, 0, 0, 255))
            draw = ImageDraw.Draw(placeholder)
            draw.rectangle([0, 0, 99, 99], outline=(0, 0, 0, 255), width=2)
            draw.text((10, 40), "失败", fill=(255, 255, 255, 255))
            return placeholder
    
    def _apply_transformations(self, image, user_data):
        """应用变换"""
        if image.mode != 'RGBA':
            image = image.convert('RGBA')
        
        # 尺寸
        dimension = user_data.get('dimension', {})
        if dimension.get('width') and dimension.get('height'):
            new_size = (int(dimension['width']), int(dimension['height']))
            image = image.resize(new_size, Image.Resampling.LANCZOS)
        
        # 旋转
        angle = user_data.get('angle_of_rotation', 0)
        if angle != 0:
            image = image.rotate(angle, expand=True, fillcolor=(0, 0, 0, 0))
        
        return image
    
    def _save_photoshop_compatible_tiff(self, original_image, original_layers_info, json_layers, export_path):
        """
        保存兼容Photoshop的TIFF文件
        策略：保留原始TIFF数据，然后添加新图层
        """
        try:
            if not json_layers:
                # 如果没有新图层，直接复制原始文件
                if original_image:
                    original_image.save(export_path, 'TIFF', compression='lzw')
                    print(f"保存原始TIFF（无新图层）: {export_path}")
                    return export_path
            
            # 如果有新图层，需要合成
            if original_image:
                # 从原始图片开始
                composite = original_image.copy()
            else:
                # 创建空白画布
                composite = Image.new('RGBA', (800, 600), (255, 255, 255, 255))
            
            # 合成所有JSON图层
            for json_layer in json_layers:
                composite = Image.alpha_composite(composite, json_layer)
            
            # 保存合成结果
            composite.save(export_path, 'TIFF', compression='lzw')
            
            print(f"保存合成TIFF: {export_path}")
            print(f"原始图层信息: {len(original_layers_info)} 个")
            print(f"新增JSON图层: {len(json_layers)} 个")
            print("注意：由于技术限制，图层已合并。要完全保留Photoshop图层，建议使用PSD格式。")
            
            return export_path
            
        except Exception as e:
            print(f"保存TIFF失败: {e}")
            raise
